/*
 * Store.java
 *
 * Created on 09-mar-2009, 0:58:06
 */

package grupb.upf.imageProcessing;

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.JPEGEncodeParam;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.media.jai.PlanarImage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>This class contains the method to store the image.</p>
 *
 * @version    0.0.1-SNAPSHOT
 * @author Group B
 */
public final class Store {


    /**
     * The logger. A new logger <code>grupb.upf.gui.Store</code>
     * is created to add the logs of this Store
     */
    private static final Log LOG = LogFactory.getLog(Store.class);
    /**
     * Method to store a photo.
     * @param conv_name the new name
     * @param img the image to store
     * @param qual the quality
     */
    public boolean store(String conv_name, PlanarImage img, float qual) {
        boolean flag = true;
        OutputStream out = null;
        try {
            out = new FileOutputStream(conv_name);
            //Convert to JPEG with quality selected and store
            JPEGEncodeParam encodeParam = new JPEGEncodeParam();
            encodeParam.setQuality(qual);
            ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out,
                    encodeParam);
            encoder.encode(img);
        } catch (IOException ex) {
            LOG.fatal("Error trying to save the file.", ex);
            flag = false;
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                LOG.fatal("Fatal error tryng to close the file.", ex);
                flag = false;
            }
        }
        return flag;
    }
}
